控制反转 IOC 与 DI
什么是IOC
Interversion Of Control
(控制反转)是面向对象编程中的一种设计原则:对象在被创建的时候,由一个调控系统内所有对象的外界实体,将其所依赖的对象的引用注入给它。
Intervers
- 把执行的任务和实现(
implement
)解耦。 - 使得开发者关注模块的任务设计上。
- 将模块从系统运行中抽离出来,取而代之的是契约关系。
- 防止更换模块产生副作用。
未解耦
解耦
class Wheel {
constructor(brand) {
this.brand = brand
}
}
class Car {
constructor() {
this.wheel = new Wheel('米其林')
}
run() {
console.log(`汽车用[${this.wheel.brand}]牌轮子跑`);
}
}
new Car().run();
// 使用不同品牌轮胎 ?
class Wheel {
constructor(brand) {
this.brand = brand
}
}
class Container {
constructor() { this.modules = {} }
provide(key, object) { this.modules[key] = object }
get(key) { return this.modules[key] }
}
class Car {
constructor(container) {
this.wheel = container.get('wheel');
}
run() {
console.log(`汽车用[${this.wheel.brand}]牌轮子跑`);
}
}
// 装配过程
const container = new Container();
container.provide('wheel', new Wheel('米其林'))
// container.provide('wheel', new Wheel('马牌'))
new Car(container).run();
什么依赖注入 DI
全称为 Dependency Injection
,意思是自身对象中的内置对象是通过注入的方式进行创建。
- 构造器
- Setter
- 接口注入
接口注入(Interface Injection)。通过实现某个接口,来达到设置属性的注入目的。
Nestjs 中的 IOC
providers
提供模块内依赖 通过 DI
方式注入。
user/user.service.ts
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
@Injectable()
export class UserService {
create(createUserDto: CreateUserDto) {
// 调用Modle
return 'This action adds a 🚀 new user';
}
findAll() {
return `This action returns all user`;
}
findOne(id: number) {
return `This action returns a #${id} user`;
}
update(id: number, updateUserDto: UpdateUserDto) {
return `This action updates a #${id} user`;
}
remove(id: number) {
return `This action removes a #${id} user`;
}
}
user/user.module.ts
import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { UserController } from './user.controller';
@Module({
controllers: [UserController],
providers: [UserService] // 提供者注册
})